/**
	* Created by PanJiaChen on 16/11/18.
	*/

/**
	* Parse the time to string
	* @param {(Object|string|number)} time
	* @param {string} cFormat
	* @returns {string | null}
	*/
export function parseTime(time, cFormat) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string')) {
			if ((/^[0-9]+$/.test(time))) {
				// support "1548221490638"
				time = parseInt(time)
			} else {
				// support safari
				// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
				time = time.replace(new RegExp(/-/gm), '/')
			}
		}

		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		return value.toString().padStart(2, '0')
	})
	return time_str
}

/**
	* @param {number} time
	* @param {string} option
	* @returns {string}
	*/
export function formatTime(time, option) {
	if (('' + time).length === 10) {
		time = parseInt(time) * 1000
	} else {
		time = +time
	}
	const d = new Date(time)
	const now = Date.now()

	const diff = (now - d) / 1000

	if (diff < 30) {
		return '刚刚'
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + '分钟前'
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + '小时前'
	} else if (diff < 3600 * 24 * 2) {
		return '1天前'
	}
	if (option) {
		return parseTime(time, option)
	} else {
		return (
			d.getMonth() +
			1 +
			'月' +
			d.getDate() +
			'日' +
			d.getHours() +
			'时' +
			d.getMinutes() +
			'分'
		)
	}
}

/**
	* @param {string} url
	* @returns {Object}
	*/
export function param2Obj(url) {
	const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
	if (!search) {
		return {}
	}
	const obj = {}
	const searchArr = search.split('&')
	searchArr.forEach(v => {
		const index = v.indexOf('=')
		if (index !== -1) {
			const name = v.substring(0, index)
			const val = v.substring(index + 1, v.length)
			obj[name] = val
		}
	})
	return obj
}


// 多级结构,添加字段
export function treeParse(list) {
	list.forEach((i) => {
		i.label = i.name;
		if (i.children && i.children.length) {
			treeParse(i.children);
		} else {}
		if (i.children && i.children.length === 0) delete i.children;
	});
	return list;
};

// 生成路由
export function mapPath({
	Layout,
	tables
}) {
	return tables.pages.map(i => {
		let {
			name,
			title,
			children,
			icon,
			outerLayer,
			alwaysShow = true
		} = i;
		return {
			path: `/${name}`,
			component: Layout,
			redirect: 'noRedirect',
			alwaysShow,
			outerLayer,
			module: i.module,
			name: name,
			meta: {
				title,
				icon
			},
			children: children.map(child => {
				let childPath = `${name}/${child.name}`,
					childTitle = child.title,
					perms = child.perms;
				let [, childName] = childPath.split('/');
				return {
					component: () => Promise.resolve(require(`@/views/${childPath}`).default),
					name: childName,
					hidden: child.hidden,
					icon: child.icon,
					path: childName,
					meta: {
						perms,
						title: childTitle,
						datas: tables[childName]
					}
				}
			})
		}
	})
}
/**
	* 表格合并第一列合并相同行
	* @param {*}  
	*/
export function SpanMethod({
	row,
	rowIndex,
	columnIndex
}, list, key = "category", index = 0) {
	var num = 0
	if (columnIndex == index) {
		for (var i = 0; i < list.length; i++) {
			if (row[key] == list[i][key]) {
				num++;
			}
		}
		if (num == 1) {
			return {
				rowspan: num,
				colspan: 1
			};
		} else if (num > 1) {
			if (list[rowIndex - 1] && list[rowIndex][key] == list[rowIndex - 1][key]) {
				return {
					rowspan: 0,
					colspan: 0
				}
			} else {
				return {
					rowspan: num,
					colspan: 1
				}
			}
		}
	}
};

/**
	* 图片压缩
	* @param {} params 
	*/
export function compressImg(file, e, callback) {
	let that = this;
	// headImg =null;
	//图片压缩
	let blobToFile = (dataurl, file, e, callback) => {
		let theBlob = dataURLtoBlob(dataurl);
		theBlob.lastModifiedDate = new Date();
		theBlob.name = file.name;
		callback({
				context: dataurl,
				file: theBlob,
			},
			e
		);
	};
	//将base64转换成blob
	let dataURLtoBlob = (dataurl) => {
		var arr = dataurl.split(","),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new Blob([u8arr], {
			type: mime
		});
	};
	//压缩
	let compress = (img) => {
		let canvas = document.createElement("canvas");
		let ctx = canvas.getContext("2d");
		//瓦片canvas
		let tCanvas = document.createElement("canvas");
		let tctx = tCanvas.getContext("2d");
		let initSize = img.src.length;
		let width = img.width;
		let height = img.height;
		//如果图片大于四百万像素，计算压缩比并将大小压至400万以下
		let ratio;
		if ((ratio = (width * height) / 100000000) > 1) {
			console.log("大于10000万像素");
			ratio = Math.sqrt(ratio);
			width /= ratio;
			height /= ratio;
		} else {
			ratio = 1;
		}
		canvas.width = width;
		canvas.height = height;
		//        铺底色
		ctx.fillStyle = "#fff";
		ctx.fillRect(0, 0, canvas.width, canvas.height);
		//如果图片像素大于100万则使用瓦片绘制
		let count;
		if ((count = (width * height) / 1000000) > 1) {
			console.log("超过100W像素");
			count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
			//            计算每块瓦片的宽和高
			let nw = ~~(width / count);
			let nh = ~~(height / count);
			tCanvas.width = nw;
			tCanvas.height = nh;
			for (let i = 0; i < count; i++) {
				for (let j = 0; j < count; j++) {
					tctx.drawImage(
						img,
						i * nw * ratio,
						j * nh * ratio,
						nw * ratio,
						nh * ratio,
						0,
						0,
						nw,
						nh
					);
					ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
				}
			}
		} else {
			ctx.drawImage(img, 0, 0, width, height);
		}
		//进行最小压缩
		let ndata = canvas.toDataURL("image/jpeg", 0.5);
		tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
		return ndata;
	};


	// 看支持不支持FileReader
	if (!file || !window.FileReader) return;
	if (/^image/.test(file.type)) {
		// 创建一个reader
		let reader = new FileReader();
		// 将图片2将转成 base64 格式
		reader.readAsDataURL(file);
		let headImg = {};
		// 读取成功后的回调
		reader.onloadend = function() {
			let result = this.result;
			let img = new Image();
			img.src = result;
			//判断图片是否大于100K,是就直接上传，反之压缩图片
			if (this.result.length <= 1000 * 1024) {
				headImg = this.result;
				console.log("压缩前：" + file.size);
				blobToFile(headImg, file, e, callback);
			} else {
				img.onload = function() {
					let data = compress(img);
					console.log("压缩前file：" + file.size);
					headImg = data;
					blobToFile(headImg, file, e, callback);
				};
			}
		};
	}
}

/**
	* 笛卡
	* @param  {...any} args 
	*/

import region from '@/lib/utils/region.js';
export function areaIdFnc(id, fn,arr=null) {
	//定义变量保存当前结果路径
	var temppath = [];
	var temp = [];
	try {
		function getNodePath(node) {
			temppath.push(node.name);
			temp.push(node.id);
			//找到符合条件的节点，通过throw终止掉递归
			if (node.id == id) {
				throw ("GOT IT!");
			}
			if (node.children && node.children.length > 0) {
				for (var i = 0; i < node.children.length; i++) {
					getNodePath(node.children[i]);
				}
				//当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
				temppath.pop();
				temp.pop();
			} else {

				//找到叶子节点时，删除路径当中的该叶子节点
				temppath.pop();
				temp.pop();
			}
		}
		getNodePath({
			name: '',
			children: arr || region
		});
	} catch (e) {
		let names = temppath.filter(i => i);
		let id = temp.filter(i => i);
		try {
			if (fn) fn(temp.filter(i => i), {
				id: '',
				name: names.join(" ") || '',
				names
			}, );
		} catch (error) {
			console.log('error', error);
		}
		return {
			id: id,
			name: names
		};
	}
};
export function cartesianProductOf(...args) {
	return args.reduce(
		(total, current) => {
			let ret = [];
			total.forEach(a => {
				current.forEach(b => {
					ret.push(a.concat([b]));
				});
			});
			return ret;
		},
		[
			[]
		]
	);
}